package com.lxf.complayTest.utils;

import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 *
 * 文件上传下载
 *
 * Created by Luoxingfa on 2021/9/27 0027 14:49
 */
public class FileUploadUtils {

    public static String upload(String parentName, MultipartFile uploadFile, HttpServletRequest request){

        //获取源文件地址
          String basePath = request.getServletContext().getRealPath("/static/upload/");
          //获取父文件
        String parentPath = basePath+parentName+"/";
        File parentFile = new File(parentPath);
        //判断父文件是否存在
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }
        //防止文件重名
        String fileName = System.currentTimeMillis()+parentName+getFileSuffix(uploadFile.getOriginalFilename());

        try {
                //transferTo文件上传
                uploadFile.transferTo(new File(parentPath+fileName));
        }catch (Exception e){
            e.printStackTrace();
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return "static/upload/" +parentName+"/"+fileName;
    }

    public static String getFileSuffix(String originalFilename){
        //获取最后一个小数点的位置
        int index = originalFilename.lastIndexOf(".");
        //从最后一个点开始截取
        return originalFilename.substring(index);
    }
}
